from selenium.webdriver.common.by import By
from selenium import webdriver
import datetime
import time

driver = webdriver.Edge("msedgedriver.exe")
driver.maximize_window()


def login():
    driver.get("https://www.vmall.com/product/10086009079805.html")
    time.sleep(2)
    if driver.find_element(By.LINK_TEXT, "请登录"):
        driver.find_element(By.LINK_TEXT, "请登录").click()
    print("请在20秒内完成扫码")
    time.sleep(20)
    # 点击商品
    if driver.find_element(By.XPATH, '//*[@id="pro-skus"]/dl[1]/div/ul/li[2]/div/a'):
        driver.find_element(By.XPATH, '//*[@id="pro-skus"]/dl[1]/div/ul/li[2]/div/a').click()
    else:
        print("找不到指定款式，请手动点击商品")
    if driver.find_element(By.XPATH, '//*[@id="pro-skus"]/dl[2]/div/ul/li[1]/div/a'):
        driver.find_element(By.XPATH, '//*[@id="pro-skus"]/dl[2]/div/ul/li[1]/div/a').click()
    else:
        print("找不到指定款式，请手动点击商品")
    now = datetime.datetime.now()
    print('login success:', now.strftime('%Y-%m-%d %H:%M:%S:%f'))


def buy(buytime):
    while True:
        now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
        # 对比时间，时间到的话就点击结算
        if now >= buytime:
            print("与预定时间1进行比较")
            while True:
                try:
                    # 点击购买按钮
                    print("寻找购买按钮！")
                    if driver.find_element(By.XPATH, '//div[@class="product-buttonmain"]/div[@id="pro-operation"]/span[@class="product-button02 product-agreement-style"]'):
                        driver.find_element(By.XPATH, '//div[@class="product-buttonmain"]/div[@id="pro-operation"]/span[@class="product-button02 product-agreement-style"]').click()  # 结算
                        print("程序锁定商品,结算成功")
                        break
                except:
                    time.sleep(0.001)
                    print("未找到购买按钮！")
            # 点击提交订单按钮
            while True:
                try:
                    # time.sleep(1)
                    if driver.find_element(By.XPATH, '//a[@class="order-submit-btn"]'):
                        driver.execute_script('window.scrollBy(0,250)')
                        driver.find_element(By.XPATH, '//a[@class="order-submit-btn"]').click()  # 提交订单
                        print("订单提交成功")
                        break
                except:
                    time.sleep(0.01)
            now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
            print("已经抢到商品啦，抢到的时间：" + now)
            break
        print("当前时间:" + now)
        time.sleep(0.01)


if __name__ == "__main__":
    login()
    buy("2023-09-19 18:07:59.0000")  # 本时间是抢购时间，可根据需求进行更改